﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Windows.Forms;
using System.Runtime.InteropServices;

namespace AutomationTools.Procedimentos.SimulacaoUso.Web
{
    public class SalvarPrintTela : IProcedimento
    {
        private IContexto contexto;
        public System.Windows.Forms.WebBrowser Browser
        {
            get
            {
                if (!contexto.HasMember("WebBrowser"))
                {
                    ((dynamic)contexto).WebBrowser = new WebBrowser();
                }
                return (WebBrowser)((dynamic)contexto).WebBrowser;
            }
        }

        string filePath;
        int width;
        int height;
        public SalvarPrintTela(string filePath)
            : this(filePath, Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height)
        {

        }

        public SalvarPrintTela(string filePath, int width, int height)
        {
            this.filePath = filePath;
            this.width = width;
            this.height = height;
        }

        public object Executar(IContexto contexto)
        {
            this.contexto = contexto;
            Browser.ClientSize = new Size(width >= 0 ? width : Browser.Document.Body.ScrollRectangle.Width, height >= 0 ? height : Browser.Document.Body.ScrollRectangle.Height);

            dynamic doc = Browser.Document.DomDocument;
            dynamic body = doc.body;
            IHTMLElementRender render = (IHTMLElementRender)body;
            using (Bitmap bmp = new Bitmap(Browser.ClientSize.Width, Browser.ClientSize.Height))
            {
                using (Graphics gr = Graphics.FromImage(bmp))
                {
                    IntPtr hdc = gr.GetHdc();
                    render.DrawToDC(hdc);
                    gr.ReleaseHdc();
                }
                bmp.Save(filePath);
            }

            return contexto.Parametro;
        }


        public void ValidarEntrada(IContexto contexto)
        {
            throw new NotImplementedException();
        }

        [ComImport, InterfaceType((short)1), Guid("3050F669-98B5-11CF-BB82-00AA00BDCE0B")]
        interface IHTMLElementRender
        {
            void DrawToDC(IntPtr hdc);
            void SetDocumentPrinter(string bstrPrinterName, IntPtr hdc);
        }
    }
    
}
